<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">确认订单</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 收货地址 -->
    <view class="address-section" @click="selectAddress">
      <view v-if="selectedAddress" class="address-content">
        <view class="address-info">
          <view class="address-name-phone">
            <text class="address-name">{{ selectedAddress.receiverName }}</text>
            <text class="address-phone">{{ selectedAddress.receiverPhone }}</text>
          </view>
          <view class="address-detail">
            {{ selectedAddress.receiverProvince }} {{ selectedAddress.receiverCity }} {{ selectedAddress.receiverDistrict }} {{ selectedAddress.receiverAddress }}
          </view>
        </view>
        <view class="address-right">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <view v-else class="address-empty">
        <text class="address-empty-text">请选择收货地址</text>
        <view class="address-right">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="products-section">
      <view class="section-title">
        <view class="store-info">
          <uni-icons type="shop" size="18" color="#FF8C42"></uni-icons>
          <text class="store-name">便利小店</text>
        </view>
      </view>
      
      <view class="product-list">
        <view 
          class="product-item" 
          v-for="(item, index) in selectedItems" 
          :key="index"
        >
          <image class="product-image" :src="imageFullUrl(item.productImage)" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{ item.name }}</view>
            <view class="product-specs" v-if="item.spec">{{ item.spec }}</view>
            <view class="product-price-row">
              <view class="product-price">¥{{ parseFloat(item.price).toFixed(2) }}</view>
              <view class="product-quantity">x{{ item.quantity }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="info-item">
        <text>配送方式</text>
        <text>普通快递</text>
      </view>
      <view class="info-item">
        <text>优惠券</text>
        <view class="coupon-select" @click="selectCoupon">
          <text class="coupon-text">{{ selectedCoupon ? selectedCoupon.name : '无可用优惠券' }}</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      <view class="info-item">
        <text>订单备注</text>
        <input 
          class="remark-input" 
          type="text" 
          v-model="orderRemark" 
          placeholder="选填，请先和商家协商一致" 
          maxlength="50"
        />
      </view>
    </view>
    
    <!-- 金额信息 -->
    <view class="amount-section">
      <view class="amount-item">
        <text>商品金额</text>
        <text>¥{{ totalProductAmount.toFixed(2) }}</text>
      </view>
      <view class="amount-item">
        <text>运费</text>
        <text>¥{{ shippingFee.toFixed(2) }}</text>
      </view>
      <view class="amount-item" v-if="discountAmount > 0">
        <text>优惠金额</text>
        <text class="discount-amount">-¥{{ discountAmount.toFixed(2) }}</text>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="settlement-bar">
      <view class="total-info">
        <text class="total-label">实付款:</text>
        <text class="total-price">¥{{ totalPayAmount.toFixed(2) }}</text>
      </view>
      <button 
        class="submit-btn" 
        :disabled="!canSubmit || isSubmitting"
        :class="{ 'btn-disabled': !canSubmit || isSubmitting }"
        @click="submitOrder"
      >
        {{ isSubmitting ? '提交中...' : '提交订单' }}
      </button>
    </view>

    <!-- 支付宝支付弹窗 -->
    <view v-if="showPaymentModal" class="payment-modal">
      <view class="payment-content">
        <view class="payment-header">
          <text class="payment-title">支付宝支付</text>
          <view class="payment-close" @click="closePaymentModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="payment-info">
          <text class="payment-amount">支付金额: ¥{{ totalPayAmount.toFixed(2) }}</text>
          <text class="payment-tip">请在新打开的页面完成支付</text>
        </view>
        <view class="payment-actions">
          <button class="payment-btn" @click="openAlipayPayment">打开支付宝支付</button>
          <button class="cancel-btn" @click="cancelPayment">取消支付</button>
        </view>
      </view>
    </view>

    <!-- 支付结果监听 -->
    <view v-if="showPaymentWebview" class="payment-webview-container">
      <web-view 
        ref="paymentWebview"
        :src="paymentUrl" 
        @message="handleWebviewMessage"
        @error="handleWebviewError"
        @load="handleWebviewLoad"
      ></web-view>
      <view class="webview-toolbar">
        <button class="toolbar-btn" @click="closePaymentWebview">关闭支付</button>
        <button class="toolbar-btn primary" @click="checkPaymentStatus">检查支付状态</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useUserStore } from '@/store/user';
import { useCartStore } from '@/store/cart';
import { useAddressStore } from '@/store/address';
import { getImageUrl } from '@/config/env';
import http from '@/utils/http/http.js';
import { AlipayService } from '@/utils/payment/alipay.js';
//import uni from 'uni-app'; // Declare the uni variable

// 状态栏高度
const statusBarHeight = ref(0);
const userStore = useUserStore();
const cartStore = useCartStore();
const addressStore = useAddressStore();

// 订单相关数据
const selectedItems = ref([]);
const selectedAddress = ref(null);
const selectedCoupon = ref(null);
const orderRemark = ref('');
const shippingFee = ref(0);
const isSubmitting = ref(false);

// 支付相关数据
const showPaymentModal = ref(false);
const showPaymentWebview = ref(false);
const currentOrderNo = ref('');
const alipayFormData = ref('');
const paymentUrl = ref('');
const paymentWebview = ref(null);

// 生成完整的图片 URL
const imageFullUrl = getImageUrl;

// 计算商品总金额
const totalProductAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (parseFloat(item.price) * item.quantity);
  }, 0);
});

// 计算优惠金额
const discountAmount = computed(() => {
  if (selectedCoupon.value) {
    return selectedCoupon.value.amount || 0;
  }
  return 0;
});

// 计算实付金额
const totalPayAmount = computed(() => {
  return totalProductAmount.value + shippingFee.value - discountAmount.value;
});

// 判断是否可以提交订单
const canSubmit = computed(() => {
  return selectedItems.value.length > 0 && selectedAddress.value;
});

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 选择收货地址
const selectAddress = () => {
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url: '/pages/address/address-select'
  });
};

// 选择优惠券
const selectCoupon = () => {
  uni.showToast({
    title: '暂无可用优惠券',
    icon: 'none'
  });
};

// 提交订单
const submitOrder = async () => {
  if (!canSubmit.value || isSubmitting.value) return;
  
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  if (!selectedAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    });
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    // 获取选中商品的购物车ID列表
    const selectedCartIds = selectedItems.value.map(item => item.id).filter(id => id);
    
    // 构建订单数据
    const orderData = {
      shippingId: selectedAddress.value.id,
      selectedCartItems: selectedCartIds,
      remark: orderRemark.value || "订单备注"
    };
    
    console.log('提交的订单数据:', JSON.stringify(orderData));
    
    // 发送创建订单请求
    const response = await http.post('/api/orders/create', orderData, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      // 订单创建成功
      currentOrderNo.value = response.data;
      
      // 清空已选中的购物车商品
      await cartStore.removeSelectedItems();
      
      // 发起支付宝支付
      await initiateAlipayPayment(currentOrderNo.value);
      
    } else {
      uni.showToast({
        title: response.message || '创建订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('提交订单失败:', error);
    uni.showToast({
      title: '提交订单失败，请重试',
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};

// 发起支付宝支付
const initiateAlipayPayment = async (orderNo) => {
  try {
    const paymentData = {
      orderNo: orderNo,
      paymentType: 2 // 支付宝支付
    };
    
    console.log('发起支付宝支付:', paymentData);
    
    const response = await http.post('/api/orders/pay', paymentData, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data && response.data.payUrl) {
      // 保存支付表单数据
      alipayFormData.value = response.data.payUrl;
      
      // 显示支付弹窗
      showPaymentModal.value = true;
      
      console.log('支付宝支付请求成功');
    } else {
      uni.showToast({
        title: response.message || '发起支付失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('发起支付宝支付失败:', error);
    uni.showToast({
      title: '发起支付失败，请重试',
      icon: 'none'
    });
  }
};

// 打开支付宝支付页面 - 改进版本
const openAlipayPayment = async () => {
  try {
    if (!alipayFormData.value) {
      uni.showToast({
        title: '支付数据异常',
        icon: 'none'
      });
      return;
    }

    // 关闭支付弹窗
    showPaymentModal.value = false;

    // #ifdef MP-WEIXIN
    // 微信小程序中，复制支付链接
    uni.setClipboardData({
      data: alipayFormData.value,
      success: () => {
        uni.showModal({
          title: '支付提示',
          content: '支付链接已复制，请在浏览器中打开完成支付',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
    // #endif
    
    // #ifdef H5
    // H5环境中，直接打开新窗口
    const payWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
    if (payWindow) {
      payWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>支付宝支付</title>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body>
          <div style="text-align: center; padding: 20px;">
            <h3>正在跳转到支付宝支付页面...</h3>
            <p>如果没有自动跳转，请点击下方按钮</p>
          </div>
          ${alipayFormData.value}
          <script>
            // 自动提交表单
            setTimeout(() => {
              const form = document.querySelector('form');
              if (form) {
                form.submit();
              }
            }, 1000);
          <\/script>
        <\/body>
        <\/html>
      `);
      payWindow.document.close();
    }
    // #endif
    
    // #ifdef APP-PLUS
    // App环境中的多种处理方式
    await handleAppAlipayPayment();
    // #endif
    
    // 跳转到支付结果页面
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
      });
    }, 2000);
    
  } catch (error) {
    console.error('打开支付宝支付页面失败:', error);
    uni.showToast({
      title: '打开支付页面失败',
      icon: 'none'
    });
  }
};

// App环境中的支付宝支付处理 - 浏览器优先方案
const handleAppAlipayPayment = async () => {
  try {
    console.log('使用浏览器支付方案');
    
    // 直接使用浏览器支付，不再尝试原生调用
    const alipayService = new AlipayService();
    const result = await alipayService.pay(alipayFormData.value);
    handlePaymentResult(result);
    
  } catch (error) {
    console.error('浏览器支付失败:', error);
    
    // 显示用户友好的错误信息
    uni.showModal({
      title: '支付提示',
      content: '无法打开支付页面，请检查设备是否安装浏览器应用',
      showCancel: true,
      cancelText: '取消',
      confirmText: '重试',
      success: (res) => {
        if (res.confirm) {
          // 重试支付
          handleAppAlipayPayment();
        } else {
          // 取消支付
          cancelPayment();
        }
      }
    });
  }
};

// 使用WebView打开支付页面 - 修复版本
const openPaymentWebview = async () => {
  try {
    // #ifdef APP-PLUS
    // 检查plus环境
    if (!plus || !plus.webview) {
      throw new Error('WebView环境不可用');
    }
    
    // 创建支付页面HTML
    const paymentHtml = createPaymentHtml();
    
    // 创建WebView
    const webview = plus.webview.create('', 'alipay-payment', {
      top: '0px',
      bottom: '100px',
      left: '0px',
      right: '0px',
      background: '#ffffff',
      scrollIndicator: 'none',
      bounce: 'none'
    });
    
    // 加载支付页面
    webview.loadData(paymentHtml, 'text/html', 'UTF-8');
    
    // 显示WebView
    webview.show('slide-in-right', 300);
    
    // 添加工具栏
    addWebViewToolbar(webview);
    
    // 监听WebView事件 - 添加错误处理
    webview.addEventListener('loaded', () => {
      console.log('支付页面加载完成');
    });
    
    webview.addEventListener('error', (error) => {
      console.error('支付页面加载失败:', error);
      webview.close();
      uni.showToast({
        title: '支付页面加载失败',
        icon: 'none'
      });
    });
    
    webview.addEventListener('close', () => {
      console.log('支付页面已关闭');
    });
    
    // #endif
    
    // #ifndef APP-PLUS
    // 非App环境使用内置WebView组件
    const paymentHtml = createPaymentHtml();
    const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(paymentHtml);
    paymentUrl.value = dataUrl;
    showPaymentWebview.value = true;
    // #endif
    
  } catch (error) {
    console.error('创建支付WebView失败:', error);
    // 降级到复制链接方式
    fallbackToClipboard();
  }
};

// 降级到剪贴板方式
const fallbackToClipboard = () => {
  uni.showModal({
    title: '支付提示',
    content: '无法打开支付页面，是否复制支付链接到剪贴板？',
    showCancel: true,
    cancelText: '取消',
    confirmText: '复制链接',
    success: (res) => {
      if (res.confirm) {
        uni.setClipboardData({
          data: alipayFormData.value,
          success: () => {
            uni.showToast({
              title: '支付链接已复制，请在浏览器中打开',
              icon: 'none',
              duration: 3000
            });
            // 跳转到支付结果页面
            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
              });
            }, 2000);
          }
        });
      } else {
        cancelPayment();
      }
    }
  });
};

// 创建支付页面HTML
const createPaymentHtml = () => {
  return `<!DOCTYPE html>
<html>
<head>
      <title>支付宝支付</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
          font-family: -apple-system, BlinkMacSystemFont, sans-serif;
          background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%);
          min-height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }
        .container {
          background: white;
          border-radius: 20px;
          padding: 40px;
          box-shadow: 0 20px 40px rgba(0,0,0,0.1);
          text-align: center;
          max-width: 400px;
          width: 100%;
        }
        .logo {
          width: 80px;
          height: 80px;
          background: #1677ff;
          border-radius: 50%;
          margin: 0 auto 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 24px;
          font-weight: bold;
        }
        .title {
          font-size: 24px;
          color: #333;
          margin-bottom: 10px;
        }
        .subtitle {
          color: #666;
          margin-bottom: 30px;
        }
        .amount {
          font-size: 36px;
          color: #1677ff;
          font-weight: bold;
          margin-bottom: 30px;
        }
        .btn {
          width: 100%;
          height: 50px;
          background: #1677ff;
          color: white;
          border: none;
          border-radius: 25px;
          font-size: 16px;
          font-weight: bold;
          cursor: pointer;
          transition: all 0.3s ease;
          margin-bottom: 15px;
        }
        .btn:hover {
          background: #0958d9;
          transform: translateY(-2px);
        }
        .btn:active {
          transform: translateY(0);
        }
        .cancel-btn {
          background: #f5f5f5;
          color: #666;
        }
        .cancel-btn:hover {
          background: #e6e6e6;
        }
        .form-container {
          display: none;
        }
        .loading {
          display: none;
          margin: 20px 0;
        }
        .spinner {
          border: 3px solid #f3f3f3;
          border-top: 3px solid #1677ff;
          border-radius: 50%;
          width: 30px;
          height: 30px;
          animation: spin 1s linear infinite;
          margin: 0 auto;
        }
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        .status {
          margin: 20px 0;
          color: #666;
          font-size: 14px;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="logo">支</div>
        <h2 class="title">支付宝支付</h2>
        <p class="subtitle">安全便捷的支付体验</p>
        
        <div id="payment-content">
          <div class="amount">¥${totalPayAmount.value.toFixed(2)}</div>
          <div class="status">订单号: ${currentOrderNo.value}</div>
          <button class="btn" onclick="startPayment()">确认支付</button>
          <button class="btn cancel-btn" onclick="cancelPayment()">取消支付</button>
        </div>
        
        <div class="loading" id="loading">
          <div class="spinner"></div>
          <p>正在跳转到支付宝...</p>
        </div>
        
        <div class="form-container">
          ${alipayFormData.value}
        </div>
      </div>
      
      <script>
        function startPayment() {
          document.getElementById('payment-content').style.display = 'none';
          document.getElementById('loading').style.display = 'block';
          
          setTimeout(() => {
            const form = document.querySelector('form');
            if (form) {
              form.submit();
            } else {
              alert('支付数据异常，请重试');
              resetPayment();
            }
          }, 1500);
        }
        
        function cancelPayment() {
          if (confirm('确定要取消支付吗？')) {
            // 通知原生应用取消支付
            try {
              if (window.plus && plus.webview) {
                plus.webview.currentWebview().close();
              } else if (window.parent) {
                window.parent.postMessage({ action: 'cancel' }, '*');
              }
            } catch (e) {
              console.log('关闭支付页面失败:', e);
            }
          }
        }
        
        function resetPayment() {
          document.getElementById('payment-content').style.display = 'block';
          document.getElementById('loading').style.display = 'none';
        }
        
        // 页面加载完成后的处理
        window.onload = function() {
          console.log('支付页面加载完成');
        };
        
        // 监听页面可见性变化 - 添加错误处理
        try {
          if (document.addEventListener) {
            document.addEventListener('visibilitychange', function() {
              if (!document.hidden) {
                console.log('页面重新可见');
              }
            });
          }
        } catch (e) {
          console.log('无法添加可见性监听器:', e);
        }
      <\/script>
    <\/body>
    <\/html>
  `;
};

// 添加WebView工具栏 - App环境
const addWebViewToolbar = (webview) => {
  // #ifdef APP-PLUS
  try {
    const toolbar = plus.nativeObj.createView('toolbar', {
      top: (plus.screen.resolutionHeight - 100) + 'px',
      left: '0px',
      width: '100%',
      height: '100px',
      backgroundColor: '#ffffff'
    });

    // 绘制分割线
    toolbar.drawRect({
      color: '#e5e5e5',
      radius: '0px'
    }, {
      top: '0px',
      left: '0px',
      width: '100%',
      height: '1px'
    });

    // 绘制关闭按钮
    toolbar.drawText('关闭支付', {
      top: '20px',
      left: '20px',
      width: '100px',
      height: '60px'
    }, {
      size: '16px',
      color: '#666666',
      align: 'center'
    });

    // 绘制检查状态按钮
    toolbar.drawText('检查支付状态', {
      top: '20px',
      right: '20px',
      width: '120px',
      height: '60px'
    }, {
      size: '16px',
      color: '#1677ff',
      align: 'center'
    });

    // 添加点击事件
    toolbar.addEventListener('click', (event) => {
      if (event.clientX < 140) {
        // 关闭支付
        webview.close();
        toolbar.close();
        cancelPayment();
      } else if (event.clientX > (plus.screen.resolutionWidth - 140)) {
        // 检查支付状态
        checkPaymentStatus();
      }
    });

    toolbar.show();

    // 当WebView关闭时，也关闭工具栏
    webview.addEventListener('close', () => {
      toolbar.close();
    });
  } catch (error) {
    console.error('创建工具栏失败:', error);
  }
  // #endif
};
// 创建临时HTML文件
const createTempHtmlFile = (htmlContent) => {
  return new Promise((resolve, reject) => {
    // #ifdef APP-PLUS
    const fs = plus.io.requestFileSystem(plus.io.PRIVATE_WWW, fs => {
      fs.root.getFile('payment.html', { create: true }, fileEntry => {
        fileEntry.createWriter(writer => {
          writer.onwrite = () => {
            resolve(fileEntry.toLocalURL());
          };
          writer.onerror = reject;
          writer.write(htmlContent);
        });
      }, reject);
    }, reject);
    // #endif
    
    // #ifndef APP-PLUS
    // 非App环境，使用data URL
    const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(htmlContent);
    resolve(dataUrl);
    // #endif
  });
};

// 处理WebView消息
const handleWebviewMessage = (event) => {
  console.log('WebView消息:', event.detail.data);
  const data = event.detail.data[0];
  
  if (data.action === 'checkPayment') {
    checkPaymentStatus();
  }
};

// 处理WebView错误
const handleWebviewError = (error) => {
  console.error('WebView错误:', error);
  uni.showToast({
    title: '支付页面加载失败',
    icon: 'none'
  });
};

// 处理WebView加载完成
const handleWebviewLoad = () => {
  console.log('WebView加载完成');
};

// 关闭支付WebView
const closePaymentWebview = () => {
  showPaymentWebview.value = false;
  paymentUrl.value = '';
};

// 检查支付状态
const checkPaymentStatus = async () => {
  try {
    const response = await http.get(`/api/orders/payment-status/${currentOrderNo.value}`, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200) {
      const paymentStatus = response.data.status;
      
      if (paymentStatus === 'SUCCESS') {
        closePaymentWebview();
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          uni.redirectTo({
            url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
          });
        }, 1500);
      } else if (paymentStatus === 'FAILED') {
        uni.showToast({
          title: '支付失败',
          icon: 'none'
        });
      } else {
        uni.showToast({
          title: '支付状态确认中...',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('检查支付状态失败:', error);
    uni.showToast({
      title: '检查支付状态失败',
      icon: 'none'
    });
  }
};

// 处理支付结果
const handlePaymentResult = (result) => {
  console.log('支付结果:', result);
  
  if (result.resultStatus === '9000') {
    // 支付成功
    uni.showToast({
      title: '支付成功',
      icon: 'success'
    });
    
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/orders/success?orderNo=${currentOrderNo.value}`
      });
    }, 1500);
  } else if (result.resultStatus === '6001') {
    // 用户取消支付
    uni.showToast({
      title: '支付已取消',
      icon: 'none'
    });
  } else {
    // 支付失败
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    });
  }
};

// 关闭支付弹窗
const closePaymentModal = () => {
  showPaymentModal.value = false;
};

// 取消支付
const cancelPayment = () => {
  showPaymentModal.value = false;
  uni.showToast({
    title: '支付已取消',
    icon: 'none'
  });
  
  uni.redirectTo({
    url: '/pages/orders/list'
  });
};

// 获取默认地址
const fetchDefaultAddress = async () => {
  try {
    await addressStore.fetchDefaultAddress();
    if (addressStore.defaultAddress) {
      selectedAddress.value = {
        id: addressStore.defaultAddress.id,
        receiverName: addressStore.defaultAddress.receiverName,
        receiverPhone: addressStore.defaultAddress.receiverPhone,
        receiverProvince: addressStore.defaultAddress.province,
        receiverCity: addressStore.defaultAddress.city,
        receiverDistrict: addressStore.defaultAddress.district,
        receiverAddress: addressStore.defaultAddress.detailAddress,
        isDefault: addressStore.defaultAddress.isDefault
      };
    }
  } catch (error) {
    console.error('获取默认地址失败:', error);
  }
};

// 初始化数据
const initData = async () => {
  selectedItems.value = cartStore.cartItems.filter(item => item.selected === 1);
  
  if (selectedItems.value.length === 0) {
    uni.showToast({
      title: '请先选择商品',
      icon: 'none'
    });
    uni.navigateBack();
    return;
  }
  
  await fetchDefaultAddress();
};

// 监听地址存储中的当前地址变化
watch(() => addressStore.currentAddress, (newAddress) => {
  if (newAddress) {
    selectedAddress.value = newAddress;
  }
}, { deep: true });

// 页面加载时执行
onMounted(() => {
  console.log('结算页面已挂载');
  getStatusBarHeight();
  initData();
});
</script>

<style>
.container {
  padding-bottom: 120rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  padding: 0 20rpx;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 收货地址 */
.address-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
}

.address-content {
  flex: 1;
  display: flex;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-name-phone {
  margin-bottom: 10rpx;
}

.address-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.address-phone {
  font-size: 28rpx;
  color: #666;
}

.address-detail {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

.address-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.address-empty-text {
  font-size: 28rpx;
  color: #999;
}

.address-right {
  margin-left: 20rpx;
}

/* 商品列表 */
.products-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  padding: 10rpx 0;
  border-bottom: 1rpx solid #FFE6CC;
  margin-bottom: 20rpx;
}

.store-info {
  display: flex;
  align-items: center;
}

.store-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}

.product-list {
  padding: 10rpx 0;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  position: relative;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-specs {
  font-size: 24rpx;
  color: #999;
  background-color: #FFF0E0;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  display: inline-block;
  margin-bottom: 16rpx;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 30rpx;
  color: #FF8C42;
  font-weight: bold;
}

.product-quantity {
  font-size: 26rpx;
  color: #999;
}

/* 订单信息 */
.order-info-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item text:first-child {
  font-size: 28rpx;
  color: #333;
}

.info-item text:last-child {
  font-size: 28rpx;
  color: #666;
}

.coupon-select {
  display: flex;
  align-items: center;
}

.coupon-text {
  font-size: 28rpx;
  color: #FF8C42;
  margin-right: 10rpx;
}

.remark-input {
  text-align: right;
  font-size: 28rpx;
  color: #666;
  width: 400rpx;
}

/* 金额信息 */
.amount-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
}

.amount-item text:first-child {
  font-size: 28rpx;
  color: #333;
}

.amount-item text:last-child {
  font-size: 28rpx;
  color: #666;
}

.discount-amount {
  color: #FF8C42 !important;
}

/* 底部结算栏 */
.settlement-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border-top: 1rpx solid #FFE6CC;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.total-info {
  flex: 1;
  display: flex;
  align-items: baseline;
}

.total-label {
  font-size: 28rpx;
  color: #333;
  margin-right: 10rpx;
}

.total-price {
  font-size: 36rpx;
  color: #FF8C42;
  font-weight: bold;
}

.submit-btn {
  min-width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-left: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
  transition: all 0.3s ease;
}

.submit-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(255, 140, 66, 0.2);
}

.btn-disabled {
  background: linear-gradient(to right, #CCCCCC, #DDDDDD);
  box-shadow: none;
}

/* 支付弹窗样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.payment-content {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin: 40rpx;
  max-width: 600rpx;
  width: 100%;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.payment-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.payment-close {
  padding: 10rpx;
}

.payment-info {
  text-align: center;
  margin-bottom: 40rpx;
}

.payment-amount {
  display: block;
  font-size: 36rpx;
  color: #FF8C42;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.payment-tip {
  display: block;
  font-size: 26rpx;
  color: #666;
}

.payment-actions {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.payment-btn {
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #1677ff, #40a9ff);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: none;
}

.cancel-btn {
  height: 80rpx;
  line-height: 80rpx;
  background-color: #f5f5f5;
  color: #666;
  font-size: 28rpx;
  border-radius: 40rpx;
  border: none;
}

/* WebView支付容器 */
.payment-webview-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 10000;
}

.webview-toolbar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.toolbar-btn {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border-radius: 35rpx;
  font-size: 28rpx;
  margin: 0 10rpx;
  border: 1rpx solid #ddd;
  background-color: #fff;
  color: #666;
}

.toolbar-btn.primary {
  background: linear-gradient(to right, #1677ff, #40a9ff);
  color: #fff;
  border: none;
}
</style>
